package org.jeecg.modules.meter.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.entity.charge.ChargeInvoiceRequest;
import org.jeecg.entity.meter.MeterOrder;
import org.jeecg.enums.InvoiceTypeEnum;
import org.jeecg.modules.message.service.ISysMessageService;
import org.jeecg.modules.meter.service.IMeterControlSwitchService;
import org.jeecg.modules.meter.service.IMeterOrderService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.vo.meter.MeterOrderExVo;
import org.jeecg.vo.meter.MeterSwitchRespVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 仪器充值订单表
 * @Author: liurui
 * @Date:   2020-11-27
 * @Version: V1.0
 */
@Slf4j
@Api(tags="仪器充值订单表")
@RestController
@RequestMapping("/b/meter/meterOrder")
public class MeterOrderController {
	@Autowired
	private IMeterOrderService meterOrderService;

	@Autowired
    private ISysUserRoleService sysUserRoleService;

	@Autowired
	private IMeterControlSwitchService meterControlSwitchService;

	@Autowired
	private ISysMessageService messageService;

	@Autowired
	private IFeignChargeService feignChargeService;


	/**
	  * 分页列表查询
	 * @param meterOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "仪器充值订单表-分页列表查询")
	@ApiOperation(value="仪器充值订单表-分页列表查询", notes="仪器充值订单表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<MeterOrder>> queryPageList(MeterOrder meterOrder,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<MeterOrder>> result = new Result<IPage<MeterOrder>>();
		meterOrder.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",meterOrder.getMenuPath(),null,meterOrder.getDepartIdEx()));
		Page<MeterOrder> page = new Page<MeterOrder>(pageNo, pageSize);
		page.setRecords(meterOrderService.findPage(page, meterOrder));
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}

	 @AutoLog(value = "仪器充值订单表-查询明细")
	 @ApiOperation(value="仪器充值订单表-查询明细", notes="仪器充值订单表-查询明细")
	 @RequestMapping(value = "/getEvidence")
	public Result<MeterOrder> getEvidence(@RequestParam(name="orderId",required=true) String orderId){
		try {
			return meterOrderService.getEvidence(orderId);
		}catch (Exception e){
			log.error("操作失败",e.getMessage());
			return Result.error("操作失败!");
		}
	}

	@AutoLog(value = "仪器充值发票")
	@ApiOperation(value="仪器充值发票", notes="仪器充值发票")
	@RequestMapping(value = "/getInvoiceList")
	public Result<List<ChargeInvoiceRequest>> getInvoiceList(@RequestParam(name = "orderNum", required = true) String orderNum){
		try {
			List<ChargeInvoiceRequest> list = meterOrderService.invoiceRequestListBySn(orderNum);
			return Result.ok(list);
		}catch (Exception ex){
			log.error("操作失败", ex.getMessage());
			return Result.error("操作失败！");
		}
	}

	@AutoLog(value = "发票红冲")
	@ApiOperation(value="发票红冲", notes="发票红冲")
	@RequestMapping(value = "/redInvoice")
	public Result redInvoice(@RequestParam(name = "lsh", required = true) String lsh){
		try {
			ChargeInvoiceRequest req = meterOrderService.invoiceRequestByFpqqlsh(lsh);
			boolean b = feignChargeService.openRed(JSON.toJSONString(req), req.getTenantId());
			if (b){
				return Result.ok("红冲成功");
			}
			return Result.ok("红冲失败");
		}catch (Exception ex) {
			log.error("操作失败", ex.getMessage());
			return Result.error("红冲失败！");
		}
	}

	@AutoLog(value = "发票补开")
	@ApiOperation(value="发票补开", notes="发票补开")
	@RequestMapping(value = "/blueInvoice")
	public Result blueInvoice(@RequestBody MeterOrder meterOrder){
		try {
			MeterOrder order = meterOrderService.getById(meterOrder.getId());
			if (order == null) return Result.error("订单在系统中不存在!");
			boolean isOpenBlue = feignChargeService.isOpenBlue(order.getSn(),order.getTenantId());
			if (isOpenBlue) return Result.error("当前订单已开票,请勿重复开票!");
			order.setInvoiceStatus(Integer.valueOf(InvoiceTypeEnum.INVOICE_TYPE_ELE.getCode()));
			order.setInvoiceName(meterOrder.getInvoiceName());
			order.setInvoiceEmail(meterOrder.getInvoiceEmail());
			order.setInvoiceEin(meterOrder.getInvoiceEin());
			Result result = meterOrderService.meterBlueInvoice(order);
			return result;
		}catch (Exception ex) {
			log.error("操作失败", ex);
			return Result.error("补开失败！");
		}
	}

	 @AutoLog(value = "仪表充值订单表-退款")
	 @ApiOperation(value="仪表充值订单表-退款", notes="仪表充值订单表-退款")
	 @GetMapping(value = "/refundCharge")
	 public Result<MeterOrder> refundCharge(@RequestParam(name="orderId",required=true) String orderId) {
		 Result<MeterOrder> res = null;
		 try {
			 res = meterOrderService.refundCharge(orderId);
			 res.setMessage("退款处理成功");
			 res.setSuccess(true);
		 } catch (RuntimeException re){
			 return Result.error(re.getMessage());
		 }
		// List<MeterSwitchRespVo> meterSwitchRespVoList = res.getResult().getSwitchRespVoList();
		 // 3. 充值到实体表
		//meterChargeService.payToActualMeter(meterChargeList);
		 //4.发送送电指令
//		 meterControlSwitchService.controlSwitchMeter(meterSwitchRespVoList);
		 return res;
	 }

	/**
	  *   添加
	 * @param meterOrder
	 * @return
	 */
	@AutoLog(value = "仪表充值订单表-充值")
	@ApiOperation(value="仪表充值订单表-充值", notes="仪表充值订单表-充值")
	@PostMapping(value = "/unLineCharge")
	public Result<MeterOrder> unLineCharge(@RequestBody MeterOrder meterOrder) {

		Result<MeterOrder> res = null;
		try {
			res = meterOrderService.unLineCharge(meterOrder);
		} catch (Exception re){
			return Result.error("系统繁忙，充值失败！");
		}
		//开发票
//		invoiceHandler(res.getData().getId(),reqVo, userInfo);
//		List<MeterChargeRespVo> meterChargeList = res.getData().getMeterChargeRespVoList();
		List<MeterSwitchRespVo> meterSwitchRespVoList = res.getResult().getSwitchRespVoList();

		// 3. 充值到实体表
//		meterChargeService.payToActualMeter(meterChargeList);
		//4.发送送电指令
		meterControlSwitchService.controlSwitchMeter(meterSwitchRespVoList);
		// 开电票
		meterOrderService.meterBlueInvoice(res.getResult());
		return Result.ok("充值处理成功");
	}

	 /**
	  *   扫码枪
	  * @param meterOrder
	  * @return
	  */
	 @AutoLog(value = "仪表充值订单表-扫码枪充值")
	 @ApiOperation(value="仪表充值订单表-扫码枪充值", notes="仪表充值订单表-扫码枪充值")
	 @PostMapping(value = "/unLineQRCodeCharge")
	 @ResponseBody
	 public Result<MeterOrder> unLineQRCodeCharge(@RequestBody MeterOrder meterOrder) throws Exception {
	 	log.info("扫码枪充值接受参数:{}",meterOrder);
		 Result<MeterOrder> result = null;
		 try {
		     result = meterOrderService.unLineQRCodeCharge(meterOrder);
              return result;
         }catch (Exception ex){
             return Result.error("系统繁忙，充值失败！");
         }
	 }

	 @ApiOperation(value = "查询付费通订单支付状态")
	 @GetMapping(value = "/checkOrderByTransNo")
	 public Result<Object> checkOrderByTransNo(@RequestParam(name="projectId",required=true) String projectId,
											   @RequestParam(name="transNo",required=true) String transNo){
	 	Result<Object> result = null;
	 	try {
	 		result = meterOrderService.checkOrderByTransNo(projectId, transNo);
		}catch (Exception ex){
			return Result.error("订单查询异常！");
		}
	 	return result;
	 }
	
	/**
	  *  编辑
	 * @param meterOrder
	 * @return
	 */
	@AutoLog(value = "仪器充值订单表-编辑")
	@ApiOperation(value="仪器充值订单表-编辑", notes="仪器充值订单表-编辑")
	@PutMapping(value = "/edit")
	public Result<MeterOrder> edit(@RequestBody MeterOrder meterOrder) {
		Result<MeterOrder> result = new Result<MeterOrder>();
		MeterOrder meterOrderEntity = meterOrderService.getById(meterOrder.getId());
		if(meterOrderEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = meterOrderService.updateById(meterOrder);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "仪器充值订单表-通过id删除")
	@ApiOperation(value="仪器充值订单表-通过id删除", notes="仪器充值订单表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			meterOrderService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "仪器充值订单表-批量删除")
	@ApiOperation(value="仪器充值订单表-批量删除", notes="仪器充值订单表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<MeterOrder> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<MeterOrder> result = new Result<MeterOrder>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.meterOrderService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "仪器充值订单表-通过id查询")
	@ApiOperation(value="仪器充值订单表-通过id查询", notes="仪器充值订单表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MeterOrder> queryById(@RequestParam(name="id",required=true) String id) {
		Result<MeterOrder> result = new Result<MeterOrder>();
		MeterOrder meterOrder = meterOrderService.getById(id);
		if(meterOrder==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(meterOrder);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(MeterOrder meterOrder,HttpServletRequest request, HttpServletResponse response) throws ParseException {
	  LoginUser user = SsoUtil.getLoginUser();
	  ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
	  meterOrder.setSqlMap( sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(), "p", meterOrder.getMenuPath(), null, meterOrder.getDepartIdEx()));
	  List<MeterOrder> pageList = meterOrderService.findPage(null,meterOrder);
	  ArrayList<MeterOrderExVo> objects = Lists.newArrayList();
	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	  for (MeterOrder temp:pageList){
		  MeterOrderExVo meterOrderExVo = new MeterOrderExVo();
		  BeanUtils.copyProperties(temp,meterOrderExVo);
		  if (temp.getPayTime() != null){
			  meterOrderExVo.setPayTime(sdf.format(temp.getPayTime()));
		  }
		  if (temp.getMeterType().equals("1")){
		  	meterOrderExVo.setMeterTypeStr("电表");
		  	meterOrderExVo.setMeterPayType("电费");
		  }else {
			  meterOrderExVo.setMeterTypeStr("水表");
			  meterOrderExVo.setMeterPayType("水费");
		  }
		  objects.add(meterOrderExVo);
	  }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "仪器充值订单表列表");
      mv.addObject(NormalExcelConstants.CLASS, MeterOrderExVo.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("仪器充值订单表列表数据", "导出人:" + user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, objects);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<MeterOrder> listMeterOrders = ExcelImportUtil.importExcel(file.getInputStream(), MeterOrder.class, params);
              meterOrderService.saveBatch(listMeterOrders);
              return Result.ok("文件导入成功！数据行数:" + listMeterOrders.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
